const express=require('express');
const home=express.Router();
const {article}=require('../../modle/article')
const {comment}=require('../../modle/comment')
const pagination=require('mongoose-sex-page')

// 首页渲染
home.get('/',async (req,res)=>{
    // 获取点击分页的页码
   const {page}=req.query
    // 多集合联合查询
    let Article=await pagination(article).page(page).size(4).display(5).find().populate('author').sort({'pubishDate':-1}).exec();
    let dataStr=JSON.stringify(Article)
    Article=JSON.parse(dataStr)

    res.render('home/default',{
       Article
   })
})

// 详情页
home.get('/article',async (req,res)=>{
    const id=req.param('id');
    // const ids=req.query.id;
    // 查询详情页数据和分页
    let Article=await article.findOne({_id:id}).populate('author');
    let dataStr=JSON.stringify(Article)
    Article=JSON.parse(dataStr)

   // 查询当前文章对应的文字评论
    let Comment=await comment.find({aid:id}).populate('uid');
    let commentStr=JSON.stringify(Comment)
    Comment=JSON.parse(commentStr)
    res.render('home/article',{
        Article:Article,
        Comment:Comment
    })
})

// 提交评论
home.post('/comment',async (req,res)=>{
    // 获取表单数据
    const {uid,aid,content}=req.body;
    console.log(req.body);
    await comment.create({
        uid,
        aid,
        content,
        time:new Date()
    })
    res.redirect('/home/article?id='+aid)
})


module.exports=home
